#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from string import Template
from google.appengine.ext import db
import header
import footer
from urllib2 import *
import httplib, urllib

from Functions import Functions
from Tweet_model import GeoTweet_model

import time
import datetime
import header
import footer
import urllib2
import simplejson

class testPage(webapp.RequestHandler):
 def queryDB(self):
   tweet_list = []
   t_database = db.GqlQuery("SELECT * FROM GeoTweet_model WHERE geo!= NULL LIMIT 30") # need to fix this somehow so  it orders them by the created at date.
   for each in t_database:
     temp = ""
     tweet = str(each.text.replace("\"",""))
     tweet = tweet.replace("\\","")
     tweet = tweet.replace("'","")
     name = str(each.screen_name.replace("\"",""))
     name = name.replace("'","")
     temp += "['NAME: " + name + " TWEET: " + tweet +"',"
     #temp += "['te"+ str(each.screen_name.replace("\"",""))+"',"
     #temp += "['te"+ str(each.text.replace("\"",""))+"',"
     #temp += "['  name: Terry Dean Tweet: #bigworm? RTu201c@eancelmo: roxys mom? #lowblow. RT@DaKoolKid: @eancelmo whateva. Get yo granny. http:t./coT/EVxpKV2u201d ',"
     templatlng = each.geo
     templatlng = templatlng.replace("[","")
     templatlng = templatlng.replace("]","")
     templatlng = templatlng.split(",")
     temp += str(templatlng[0]) + "," + str(templatlng[1]) + "]"
     tweet_list.append(temp)
   return tweet_list

 # this functions gets the tweets from the database, gets their titles, lats and lons and adds to map
 def getTweets(self):
   
   samplename = ["test1","test2","test3","test4"]
   samplelat = ["-33.890542","-33.923036","-34.028249","33.80010128657071"]
   samplelon = ["151.274856","151.259052","151.157507","151.28747820854187"]
   thisstring = "\nvar tweets = [\n"
   
   #for i in range(len(samplename)):
   #  tweet_list.append("['" + samplename[i] + "'," + samplelat[i] + "," + samplelon[i] + "]")
   tweet_list = self.queryDB()
   
   for i in range(len(tweet_list)):
     if (len(tweet_list) - 1 == i):
       thisstring +=tweet_list[i] +"\n"
     else:
       thisstring +=tweet_list[i] + ",\n"
       
   thisstring += "];"
   
   return thisstring
   
 def getMap(self):
   locationstring = "northgate+college+station,+tx"	#Later can be modified to dynamic
   latlon = ""
   lat = ""
   lng = ""
   
   url_geocode_gmaps = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false' % (locationstring)	    #google maps api to get lat,lon based on location
   f_geocode_gmaps = urlopen(url_geocode_gmaps)
   while not f_geocode_gmaps:
     f = urlopen(url_geocode_gmaps)
     print "bad"
   results = simplejson.loads(f_geocode_gmaps.read())
   #print results
   for each in results['results']:
     lat = str(each['geometry']['location']['lat'])
     lng = str(each['geometry']['location']['lng'])
     #latlon += str(each['geometry']['location']['lat']) + "," + str(each['geometry']['location']['lng'])
     break
     
   head = """ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
       <html xmlns="http://www.w3.org/1999/xhtml">
       <head>
       <title>Project HootSpot</title>
       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
       <link href="stylesheets/main.css" rel="stylesheet" type="text/css" />
       
       <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
       <style type="text/css">
         html { height: 100% }
         body { height: 100%; margin: 0; padding: 0 }
         #map_canvas { height: 100% }
       </style>
       <script type="text/javascript"
           src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBf51SRNjnRRneaURosVSjdFHcGB2PCRaY&sensor=false">
       </script>
       <script type="text/javascript">
         function initialize() {"""
         
   tweetvar = self.getTweets()
   latlng = " \nvar latlng = new google.maps.LatLng("+lat + "," + lng + ");"
   tail = latlng + """
           var myOptions = {
             zoom: 12,
             center: latlng,
             mapTypeId: google.maps.MapTypeId.ROADMAP
           };
           var map = new google.maps.Map(document.getElementById("map_canvas"),
               myOptions);
           var image = 'http://dl.dropbox.com/u/12563474/Icons/Google_Maps_Marker.png'
           for (var i = 0; i < tweets.length; i++) {
             var beach = tweets[i];
             var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
             var marker = new google.maps.Marker({
                 position: myLatLng,
                 map: map,
                 icon: image,
                 title: beach[0],
             });
           }

         }   
       </script>
       </head>
       
       
       <body onload="initialize()">
       

       <div class="main">
  <div class="header">
    <div class="header_resize">
      <div class="logo">
      </div>
      
      <div class="clr"></div>
    </div>
  </div>
  
  
  <div class="hbg">
    <div class="hbg_resize">
      <div class="menu_nav">
        <ul>
          <li><a href="index.html">Home</a></li>
          <li><a href="dump_db.html">Dump Tweets</a></li>
          <li><a href="about.html">About Us</a></li>
          <li><a href="contact.html">Contact Us</a></li>
        </ul>
      </div>
    </div>
  </div>
   <div class="content">
    <div class="content_resize">
     <div class="mainbar">
      <div class="article">
		 <div id="map_canvas" style="width:600px; height:600px"></div>
		</div>
	  </div>
	 </div>
   </div>
  </div>
  
  
  
  
  
  """
   return head + tweetvar + tail + footer.foot
 def get(self):
   self.response.out.write(self.getMap())
    
if __name__ == '__main__':
  main()